﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using ReadJson.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ReadJson.ViewModels
{
    public partial class ConfigViewModel : ObservableObject
    {
       
        [ObservableProperty]
        private ObservableCollection<PLCConfig> plcConfigs = new();
        private string _currentFilePath;
        /// <summary>
        /// 构造函数ConfigViewModel
        /// </summary>
        public ConfigViewModel()
            {
                if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
                    return;

                var solutionPath = GetSolutionPath();
                if (solutionPath == null)
                {
                    MessageBox.Show("找不到解决方案目录", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                var configPath = Path.Combine(solutionPath, "plc_config.json");
                LoadConfig(configPath);
         }

        /// <summary>
        /// 载入JSON配置文件
        /// </summary>
        /// <param name="filePath"></param>
        private void LoadConfig(string filePath)
        {
                try
                {
                    if (!File.Exists(filePath))
                    {
                        MessageBox.Show("配置文件未找到", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    _currentFilePath = filePath;
                    var json = File.ReadAllText(filePath, Encoding.UTF8);
                    var configs = JsonConvert.DeserializeObject<PLCConfig[]>(json);

                    PlcConfigs.Clear();
                    if (configs != null)
                    {
                        foreach (var config in configs)
                        {
                            PlcConfigs.Add(config);
                        }
                    }
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"JSON解析错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
        }
        /// <summary>
        /// 保存JSON配置文件
        /// </summary>
        [RelayCommand]
        private void SavePLCConfig()
        {
                if (string.IsNullOrEmpty(_currentFilePath))
                {
                    MessageBox.Show("未找到配置文件路径", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                try
                {
                    var json = JsonConvert.SerializeObject(PlcConfigs, Formatting.Indented);
                    File.WriteAllText(_currentFilePath, json, Encoding.UTF8);
                    MessageBox.Show("保存成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
        }
        /// <summary>
        /// 获取解决方案路径
        /// </summary>          
        private static string GetSolutionPath()
        {
                try
                {
                    var assemblyPath = new Uri(typeof(MainViewModel).Assembly.Location).LocalPath;
                    var directory = new DirectoryInfo(Path.GetDirectoryName(assemblyPath)!);

                    // 向上回溯目录直到找到.sln文件
                    while (directory != null && !directory.GetFiles("*.sln").Any())
                    {
                        directory = directory.Parent;
                    }

                    return directory?.FullName;
                }
                catch
                {
                    return null;
                }
        }
    }
}

